from flask import Flask, request, render_template_string
import plotly.express as px
import pandas as pd
from infer import get_submission, init_model
from plot import plot_submission
import os
import warnings
warnings.filterwarnings("ignore")
from warnings import simplefilter
simplefilter(action="ignore", category=pd.errors.PerformanceWarning)
from wsgiref.simple_server import make_server  

app = Flask(__name__)
model_path = os.path.dirname(os.path.abspath(__file__)) + "/model_best.pth"
model = init_model(model_path)

# HTML模板，用于显示表格内容和图表
HTML_TEMPLATE = '''
<!doctype html>
<html>
<head>
    <title>睡眠监测系统</title>
</head>
<body>
    <h1>睡眠监测系统</h1>
    <button onclick="window.history.back();">返回上一级</button>
    <h2>传感器数据预览：</h2>
    <pre>{{ first_rows }}</pre>
    <span>......</span>
    <pre>{{ last_rows }}</pre>
    <h2> 预测结果： </h2>
    <pre>{{ submission_str }}</pre>
    <h2>传感器绘图:</h2>
    {{ plot_html|safe }}
</body>
</html>
'''

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'No file part in the request'
        file = request.files['file']
        if file.filename == '':
            return 'No selected file'
        if file and file.filename.endswith('.parquet'):
            df = pd.read_parquet(file)
            first_rows = df.head().to_string(index=False)
            last_rows = df.tail().to_string(index=False)

            submission = get_submission(df, model)
            submission_str = submission.to_string(index=False)
            plot_html = plot_submission(submission, df)

            return render_template_string(HTML_TEMPLATE, first_rows=first_rows, last_rows=last_rows, submission_str = submission_str, plot_html=plot_html)
    return '''
    <!doctype html>
    <html>
    <head>
        <title>睡眠监测系统</title>
    </head>
    <body>
        <h1>请上传一个传感器数据Parquet文件</h1>
        <form method=post enctype=multipart/form-data>
          <input type=file name=file>
          <input type=submit value=Upload>
        </form>
    </body>
    </html>
    '''

if __name__ == '__main__':  
    httpd = make_server('0.0.0.0', 5000, app)  
    httpd.serve_forever()